package com.yc.zk.test;

import lombok.Data;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class App {
    public static void main(String[] args) {

        List<String> list = Arrays.asList("1", "1.1", "1.2", "1.2.1", "1.2.3", "1.3", "1.3.1", "1.3.2", "2", "2.1", "2.2", "2.2.1");

        List<String> topList = list.stream().filter(d -> d.indexOf(".") < 0).collect(Collectors.toList());
        List<Tree> treeList = new ArrayList<>();
        for (String s : topList) {
            treeList.add(new Tree(s, fillSon(s, list)));
        }
        System.out.println(treeList);
    }

    private static List<Tree> fillSon(String parent, List<String> list) {
        int pointNo = countNum("\\.", parent);
        List<String> sonList = list.stream()
                .filter(d -> d.indexOf(parent + ".") == 0 && countNum("\\.", d) == pointNo + 1).collect(Collectors.toList());
        if (sonList != null && sonList.isEmpty() == false) {
            List<Tree> treeList = new ArrayList<>();
            for (String s : sonList) {
                treeList.add(new Tree(s, fillSon(s, list)));
            }
            return treeList;
        }
        return null;
    }

    /**
     * 计算字符串中包含多少个正则表达式匹配的字符段
     *
     * @param regex 正则表达式
     * @param input 字符串
     */
    public static int countNum(String regex, String input) {
        Matcher m = Pattern.compile(regex).matcher(input);
        int count = 0;
        while (m.find()) {
            count++;
        }
        return count;
    }
}

@Data
class Tree {
    private String str;
    private List<Tree> children;

    public Tree(String str, List<Tree> children) {
        this.str = str;
        this.children = children;
    }
}
